package com.luke.web.controller.base;

import java.util.*;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.luke.base.bo.DataCount;
import com.luke.base.domain.RetrieveAlarm;
import com.luke.base.domain.vo.EquipmentModel;
import com.luke.base.domain.vo.Location;
import com.luke.base.service.ILkUserService;
import com.luke.base.service.IRetrieveAlarmService;
import com.luke.common.utils.DateUtils;
import com.luke.web.controller.util.HttpStatusException;
import com.luke.web.controller.util.LukeApiUtil;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.luke.common.annotation.Log;
import com.luke.common.core.controller.BaseController;
import com.luke.common.core.domain.AjaxResult;
import com.luke.common.enums.BusinessType;
import com.luke.base.domain.LkEquipment;
import com.luke.base.service.ILkEquipmentService;
import com.luke.common.utils.poi.ExcelUtil;
import com.luke.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 设备管理Controller
 * 
 * @author luke
 * @date 2021-05-30
 */
@RestController
@RequestMapping("/base/equipment")
public class LkEquipmentController extends BaseController
{
    @Autowired
    private ILkEquipmentService lkEquipmentService;
    @Autowired
    private IRetrieveAlarmService retrieveAlarmService;
    @Autowired
    private ILkUserService lkUserService;

    /**
     * 查询设备管理列表
     */
    @PreAuthorize("@ss.hasPermi('base:equipment:list')")
    @GetMapping("/list")
    public TableDataInfo list(LkEquipment lkEquipment)
    {
        startPage();
        List<LkEquipment> list = lkEquipmentService.selectLkEquipmentList(lkEquipment);
        return getDataTable(list);
    }
    /**
     * 查询设备管理列表
     */
    @PreAuthorize("@ss.hasPermi('base:equipment:list')")
    @GetMapping("/equipmentUserList")
    public TableDataInfo equipmentUserList(LkEquipment lkEquipment)
    {
        startPage();
        List<LkEquipment> list = lkEquipmentService.selectLkEquipmentUserList(lkEquipment);
        return getDataTable(list);
    }

    /**
     * 地图查看
     */
    @PreAuthorize("@ss.hasPermi('base:equipment:list')")
    @GetMapping("/userEquipmentList")
    public AjaxResult userEquipmentList () throws HttpStatusException {
        List<LkEquipment> list = lkEquipmentService.selectLkEquipmentUserList(new LkEquipment());
        //查询全部设备定位
        List<Location> locationList=LukeApiUtil.LocationPaging();
        //转换成map方便匹配
        Map<String,Location> locationMap=new HashMap<>();
        for (Location location : locationList) {
            locationMap.put(location.getCar_id(),location);
        }
        for (LkEquipment equipment : list) {
            equipment.setLocation(locationMap.get(equipment.getEquipmentNumber()));
        }
        return AjaxResult.success(list);
    }

    /**
     * 导出设备管理列表
     */
    @PreAuthorize("@ss.hasPermi('base:equipment:export')")
    @Log(title = "设备管理", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(LkEquipment lkEquipment)
    {
        List<LkEquipment> list = lkEquipmentService.selectLkEquipmentList(lkEquipment);
        ExcelUtil<LkEquipment> util = new ExcelUtil<LkEquipment>(LkEquipment.class);
        return util.exportExcel(list, "设备管理数据");
    }

    /**
     * 下载入库模板
     */
    @PreAuthorize("@ss.hasPermi('base:equipment:add')")
    @Log(title = "设备管理", businessType = BusinessType.EXPORT)
    @GetMapping("/equipmentModel")
    public AjaxResult equipmentModel()
    {
        ExcelUtil<LkEquipment> util = new ExcelUtil<LkEquipment>(LkEquipment.class);
        return util.importTemplateExcel("设备入库模板");
    }

    /**
     * 设备入库
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping("/importEquipmentData")
    public AjaxResult importEquipmentData(MultipartFile file) throws Exception
    {
        ExcelUtil<LkEquipment> util = new ExcelUtil<LkEquipment>(LkEquipment.class);
        List<LkEquipment> equipmentList = util.importExcel(file.getInputStream());
        String message = lkEquipmentService.importEquipment(equipmentList);
        return AjaxResult.success(message);
    }

    /**
     * 下载安装记录模板
     */
    @PreAuthorize("@ss.hasPermi('base:equipment:edit')")
    @Log(title = "设备管理", businessType = BusinessType.EXPORT)
    @GetMapping("/equipmentInstallModel")
    public AjaxResult equipmentInstallModel()
    {
        List<EquipmentModel> list = lkEquipmentService.selectLkEquipmentListUninstall();
        ExcelUtil<EquipmentModel> util = new ExcelUtil<EquipmentModel>(EquipmentModel.class);
        return util.exportExcel(list, "设备管理安装记录");
    }

    /**
     * 导入设备安装记录
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping("/importEquipmentInstallData")
    public AjaxResult importEquipmentInstallData(MultipartFile file) throws Exception
    {
        ExcelUtil<LkEquipment> util = new ExcelUtil<LkEquipment>(LkEquipment.class);
        List<LkEquipment> equipmentList = util.importExcel(file.getInputStream());
        String message = lkEquipmentService.importEquipmentInstall(equipmentList);
        return AjaxResult.success(message);
    }

    /**
     * 获取设备管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('base:equipment:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(lkEquipmentService.selectLkEquipmentById(id));
    }
    /**
     * 根绝设备编号获取未绑定的设备
     */
    @PreAuthorize("@ss.hasPermi('base:equipment:query')")
    @GetMapping(value = "/getEquipmentByNumber/{number}")
    public AjaxResult getEquipmentByNumber(@PathVariable("number") String number)
    {
        LkEquipment equipment=new LkEquipment();
        equipment=lkEquipmentService.selectLkEquipmentByNumber(number);
        return AjaxResult.success(equipment);
    }


    /**
     * 新增设备管理
     */
    @PreAuthorize("@ss.hasPermi('base:equipment:add')")
    @Log(title = "设备管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody LkEquipment lkEquipment)
    {
        return toAjax(lkEquipmentService.insertLkEquipment(lkEquipment));
    }

    /**
     * 设备绑定用户
     */
    @PreAuthorize("@ss.hasPermi('base:equipment:edit')")
    @Log(title = "设备管理", businessType = BusinessType.UPDATE)
    @PutMapping("/updateEquipmentUser")
    public AjaxResult updateEquipmentUser(@RequestBody LkEquipment lkEquipment)
    {
        return toAjax(lkEquipmentService.updateLkEquipment(lkEquipment));
    }

    /**
     * 设备解除绑定
     */
    @Log(title = "设备管理", businessType = BusinessType.UPDATE)
    @GetMapping("/unbindEquipment/{id}")
    public AjaxResult unbindEquipment(@PathVariable Long id)
    {
        LkEquipment equipment=lkEquipmentService.selectLkEquipmentById(id);
        equipment.setUserId(null);
        return toAjax(lkEquipmentService.updateLkEquipment(equipment));
    }

    /**
     * 修改设备管理
     */
    @PreAuthorize("@ss.hasPermi('base:equipment:edit')")
    @Log(title = "设备管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody LkEquipment lkEquipment)
    {
        return toAjax(lkEquipmentService.updateLkEquipment(lkEquipment));
    }


    /**
     * 删除设备管理
     */
    @PreAuthorize("@ss.hasPermi('base:equipment:remove')")
    @Log(title = "设备管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        int count=lkEquipmentService.deleteLkEquipmentByIds(ids);
        if(count>0){
            return AjaxResult.success("删除成功");
        }
        return AjaxResult.error("设备已被用户绑定,不允许删除!");
    }


    /**
     * 获取设备定位
     */
    @GetMapping(value = "/location/{equipmentNumber}")
    public AjaxResult location(@PathVariable("equipmentNumber") String equipmentNumber) throws HttpStatusException {
        return LukeApiUtil.location(equipmentNumber);
    }
    /**
     * 获取设备信息
     */
    @GetMapping(value = "/status/{equipmentNumber}")
    public AjaxResult status(@PathVariable("equipmentNumber") String equipmentNumber) throws HttpStatusException {
        return LukeApiUtil.status(equipmentNumber);
    }
    /**
     * 历史轨迹
     */
    @GetMapping(value = "/track")
    public AjaxResult track(@RequestParam("equipmentNumber") String equipmentNumber, @RequestParam("startTime")String startTime,@RequestParam("endTime") String endTime) throws HttpStatusException {
        return LukeApiUtil.track(equipmentNumber,startTime,endTime);
    }

    /**
     * 设备报警信息
     */
    @GetMapping(value = "/retrieveAlarm/{equipmentNumber}")
    public AjaxResult retrieveAlarm(@PathVariable("equipmentNumber") String equipmentNumber) throws HttpStatusException {
        RetrieveAlarm q=new RetrieveAlarm();
        q.setCar_id(equipmentNumber);
        List<RetrieveAlarm> alarmList=retrieveAlarmService.selectRetrieveAlarmList(q);
        return AjaxResult.success(alarmList);
    }

    /**
     * 车辆远程控制
     */
    @GetMapping(value = "/control")
    public AjaxResult control(@RequestParam("equipmentNumber") String equipmentNumber, @RequestParam("io")Integer io,@RequestParam("flag") String flag) throws HttpStatusException {
        return LukeApiUtil.control(equipmentNumber,io,flag);
    }

    /**
     * 获取设备信息
     */
    @GetMapping(value = "/through2/{equipmentNumber}")
    public AjaxResult through2(@PathVariable("equipmentNumber") String equipmentNumber) throws HttpStatusException {
        return LukeApiUtil.through2(equipmentNumber);
    }
    /**
     * 查询电子围栏
     */
    @GetMapping(value = "/queryvf/{equipmentNumber}")
    public AjaxResult queryvf(@PathVariable("equipmentNumber") String equipmentNumber) throws HttpStatusException {
        return LukeApiUtil.queryvf(equipmentNumber);
    }
    /**
     * 开启电子围栏
     */
    @GetMapping(value = "/openvf/{equipmentNumber}")
    public AjaxResult openvf(@PathVariable("equipmentNumber") String equipmentNumber) throws HttpStatusException {
        return LukeApiUtil.openvf(equipmentNumber);
    }
    /**
     * 关闭电子围栏
     */
    @GetMapping(value = "/closevf/{equipmentNumber}")
    public AjaxResult closevf(@PathVariable("equipmentNumber") String equipmentNumber) throws HttpStatusException {
        return LukeApiUtil.closevf(equipmentNumber);
    }
    /**
     * 车辆销量统计
     */
    @GetMapping(value = "/vehicleSaleChart")
    public AjaxResult vehicleSaleChart(){
        Calendar c= Calendar.getInstance();
        c.add(Calendar.MONTH, -11);
        String beginDate= DateUtils.parseDateToStr(DateUtils.YYYY_MM,c.getTime());
        //月份车辆销量统计
        List<DataCount> vehicleList=lkEquipmentService.vehicleSaleChart(beginDate);
        //月份用户注册数统计
        List<DataCount> userList=lkUserService.userRegisterChart(beginDate);
        //组织数据
        JSONArray dateArray=new JSONArray();
        JSONArray vehicleDataArray=new JSONArray();
        JSONArray userDataArray=new JSONArray();
        for (int i = 0; i < 12; i++) {
            String date=DateUtils.parseDateToStr(DateUtils.YYYY_MM,c.getTime());
            Integer data = 0;
            //查找当月数据
            for (DataCount dataCount : vehicleList) {
                if(date.equals(dataCount.getDate())){
                    data=dataCount.getTotalCount();
                    break;
                }
            }
            dateArray.add(date);
            vehicleDataArray.add(data);

            data = 0;
            for (DataCount dataCount : userList) {
                if(date.equals(dataCount.getDate())){
                    data=dataCount.getTotalCount();
                    break;
                }
            }
            userDataArray.add(data);
            c.add(Calendar.MONTH, 1);
        }
        JSONObject vehicle=new JSONObject();
        vehicle.put("timeData",dateArray);
        vehicle.put("expectedData",vehicleDataArray);

        JSONObject user=new JSONObject();
        user.put("timeData",dateArray);
        user.put("expectedData",userDataArray);

        AjaxResult result=AjaxResult.success();
        result.put("vehicle",vehicle);
        result.put("user",user);
        return result;
    }

    /**
     * 车辆销量统计
     */
    @GetMapping(value = "/vehicleSalePie")
    public AjaxResult vehicleSalePie(){
        List<DataCount> dataCountList=lkEquipmentService.vehicleSalePie();
        JSONArray nameArray=new JSONArray();
        JSONArray dataArray=new JSONArray();
        for (DataCount dataCount : dataCountList) {
            nameArray.add(dataCount.getVehicleModel());
            JSONObject obj = new JSONObject();
            obj.put("value",dataCount.getTotalCount());
            obj.put("name",dataCount.getVehicleModel());
            dataArray.add(obj);
        }
        JSONObject pieData=new JSONObject();
        pieData.put("name",nameArray);
        pieData.put("data",dataArray);
        return AjaxResult.success(pieData);
    }

    /**
     * 车辆销量统计
     */
    @GetMapping(value = "/vehicleSaleBar")
    public AjaxResult vehicleSaleBar(){
        Calendar c= Calendar.getInstance();
        c.add(Calendar.YEAR, -4);
        String beginDate= DateUtils.parseDateToStr(DateUtils.YYYY,c.getTime());
        //月份车辆销量统计
        List<DataCount> dataCountList=lkEquipmentService.vehicleSaleBar(beginDate);
        //组织数据
        JSONArray dateArray=new JSONArray();
        JSONArray countArray=new JSONArray();

        for (int i = 0; i < 5; i++) {
            String date=DateUtils.parseDateToStr(DateUtils.YYYY,c.getTime());
            Integer data = 0;
            //查找当月数据
            for (DataCount dataCount : dataCountList) {
                if(date.equals(dataCount.getDate())){
                    data=dataCount.getTotalCount();
                    break;
                }
            }
            dateArray.add(date);
            countArray.add(data);
            c.add(Calendar.YEAR, 1);
        }
        JSONObject object=new JSONObject();
        object.put("timeData",dateArray);
        object.put("expectedData",countArray);
        return AjaxResult.success(object);
    }

}
